<?php

class User_AddController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function preDispatch() {
        $auth = Zend_Auth::getInstance();        
        if (!$auth->hasIdentity()) {
            $this->_redirect('/user/login');
        }
        
        $view = new Zend_View();
        $view->headTitle(' > Add User');
        $this->view->userDetail = $auth->getIdentity();
    }

    public function indexAction() {
        $this->_helper->layout->disableLayout();
        
        $userModel = new Application_Model_UserModel();
        //create form
        $form = new Application_Form_users_UserForm();
        
        if($this->view->userDetail->role == 'admin'){
            $form->populate(array(
                'role'=>'user',
                'department'=>$this->view->userDetail->department
            ));
            $form->role->setAttrib('disabled', true);
            $form->department->setAttrib('disabled', true);
        }

        // if request is post
        if ($this->_request->isPost()) {
            // if form is valid

            if ($form->isValid($this->_request->getPost())) {
                $data = array(
                    'fname' => $this->_request->getPost('firstName'),
                    'lname' => $this->_request->getPost('lastName'),
                    'email' => $this->_request->getPost('email'),
                    'cell' => $this->_request->getPost('cell'),
                    'phone' => $this->_request->getPost('phone'),
                    'password' => $this->_request->getPost('password'),
                    'role' => $this->_request->getPost('role'),
                    'department' => $this->_request->getPost('department'),
                    'status' => $this->_request->getPost('status')
                );
                if ($userModel->getUser('email', $data['email'])) {

                    $this->flashMessenger->addMessage('failure');
                    $this->flashMessenger->addMessage('User address already Exist');
                    $this->_redirect("user/add");
                    exit;
                }

                $userModel->save($data);
            //    $paginator = $userModel->getAllUsers($this->_request);
             //   $this->view->paginator = $paginator;
           //     $this->_redirect("user/list"); //redirect need to change to another module
            //    exit;
            }
        }

        // assign form variable to view
        $this->view->form = $form;
    }

}